import React, { useState, useEffect } from 'react';
import { danmuStorageService } from '../services/danmuStorage';
import type { StoredDanmu } from '../services/danmuStorage';
import './DanmuManager.css';

interface DanmuManagerProps {
    onClose: () => void;
}

const DanmuManager: React.FC<DanmuManagerProps> = ({ onClose }) => {
    const [storedDanmus, setStoredDanmus] = useState<StoredDanmu[]>([]);
    const [stats, setStats] = useState({ total: 0, timeRange: { min: 0, max: 0 } });

    useEffect(() => {
        loadStoredDanmus();
    }, []);

    const loadStoredDanmus = () => {
        const danmus = danmuStorageService.getAllDanmus();
        const stats = danmuStorageService.getStats();
        setStoredDanmus(danmus);
        setStats(stats);
    };

    const deleteDanmu = (id: string) => {
        danmuStorageService.deleteDanmu(id);
        loadStoredDanmus();
    };

    const clearAllDanmus = () => {
        if (window.confirm('确定要清空所有弹幕吗？此操作不可恢复！')) {
            danmuStorageService.clearAllDanmus();
            loadStoredDanmus();
        }
    };

    const exportDanmus = () => {
        const data = danmuStorageService.exportDanmus();
        const blob = new Blob([data], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `danmu_${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    };

    const formatTime = (seconds: number) => {
        const mins = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return `${mins}:${secs.toString().padStart(2, '0')}`;
    };

    const formatDate = (timestamp: number) => {
        return new Date(timestamp).toLocaleString();
    };

    return (
        <div className="danmu-manager-overlay">
            <div className="danmu-manager-modal">
                <div className="danmu-manager-header">
                    <h2>弹幕管理</h2>
                    <button className="close-btn" onClick={onClose}>×</button>
                </div>

                <div className="danmu-manager-stats">
                    <div className="stat-item">
                        <span className="stat-label">总弹幕数:</span>
                        <span className="stat-value">{stats.total}</span>
                    </div>
                    <div className="stat-item">
                        <span className="stat-label">时间范围:</span>
                        <span className="stat-value">
                            {stats.total > 0 ? `${formatTime(stats.timeRange.min)} - ${formatTime(stats.timeRange.max)}` : '无'}
                        </span>
                    </div>
                </div>

                <div className="danmu-manager-actions">
                    <button className="action-btn export-btn" onClick={exportDanmus}>
                        导出弹幕
                    </button>
                    <button className="action-btn clear-btn" onClick={clearAllDanmus}>
                        清空所有
                    </button>
                </div>

                <div className="danmu-manager-content">
                    <div className="danmu-list">
                        {storedDanmus.length === 0 ? (
                            <div className="empty-state">
                                <p>暂无存储的弹幕</p>
                                <p>发送弹幕后会自动保存到这里</p>
                            </div>
                        ) : (
                            storedDanmus.map(danmu => (
                                <div key={danmu.id} className="danmu-item">
                                    <div className="danmu-content">
                                        <span
                                            className="danmu-text"
                                            style={{ color: danmu.color }}
                                        >
                                            {danmu.text}
                                        </span>
                                        <span className="danmu-time">{formatTime(danmu.timestamp)}</span>
                                    </div>
                                    <div className="danmu-meta">
                                        <span className="danmu-date">{formatDate(danmu.createdAt)}</span>
                                        <button
                                            className="delete-btn"
                                            onClick={() => deleteDanmu(danmu.id)}
                                            title="删除弹幕"
                                        >
                                            🗑️
                                        </button>
                                    </div>
                                </div>
                            ))
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default DanmuManager;
